import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/good/bloc/order_list_bloc.dart';
import 'package:shopping_group/modle/good/entity/shop_order4app_record_entity.dart';
import 'package:shopping_group/modle/main/bloc/details_bloc.dart';
import 'package:shopping_group/modle/main/ui/details_to_paly_page.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';

import 'good_details_page.dart';

class GoodPalyToPage extends StatefulWidget {
  GoodPalyToPage({Key key}) : super(key: key);

  @override
  _GoodPalyToPageState createState() => _GoodPalyToPageState();
}

class _GoodPalyToPageState extends State<GoodPalyToPage> {
  List<ShopOrder4AppRecordEntity> _listEntity = [];
  //listview的控制器
  ScrollController _scrollController = ScrollController();
  OrderListBloc _bloc;
  DetailsBloc _detailsBloc;
  StreamSubscription _playSubscription;
  StreamSubscription _deleteSubscription;
  String _orderId;
  String _custGroupsRelaId;
  @override
  void initState() {
    super.initState();
    _bloc = OrderListBloc();
    _detailsBloc = DetailsBloc();
    _bloc.initDate.add(BaseConstant.SOS_NO_PAY);
    _initListener();

    _playSubscription = eventBus.on<OrderPlayEvent>().listen((event) {
      if (null != event && null != event.entity) {
        event.entity
          ..openType = 'dfk'
          ..orderId = _orderId
          ..custGroupsRelaId = _custGroupsRelaId;
        RouteUtil.goParameter(DetailsToPalyPage(
          entity: event.entity,
        ));
        // }
      }
    });

    _deleteSubscription = eventBus.on<RefreshOrderEvent>().listen((event) {
      for (var item in _listEntity) {
        if (event.id == item.id) {
          _bloc.removeDate.add(item);
          break;
        }
      }
    });
  }

  _initListener() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        _bloc.moreDate.add(_scrollController);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '待支付'),
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
          color: Colours.title_white,
        ),
        child: _showlistView(),
      ),
    );
  }

  Widget _showlistView() {
    return StreamBuilder(
      stream: _bloc.sendData,
      initialData: _listEntity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is List) {
          _listEntity = object;
        }
        int count = _listEntity.length;
        if (0 != count) {
          return Container(
            decoration: new BoxDecoration(
              color: Colors.white,
            ),
            child: AnimationLimiter(
              child: RefreshIndicator(
                onRefresh: _pullToRefresh,
                child: ListView.builder(
                  controller: _scrollController,
                  shrinkWrap: true,
                  padding: const EdgeInsets.only(top: 4),
                  itemCount: _listEntity.length,
                  itemBuilder: buildItem,
                ),
              ),
            ),
          );
        } else {
          return Container(
            alignment: Alignment.center,
            child: WidgetUtils.emptyView(
              contexts,
            ),
          );
        }
      },
    );
  }

  //下拉刷新,必须异步async不然会报错
  Future _pullToRefresh() async {
    _listEntity.clear();
    _bloc.initDate.add(BaseConstant.SOS_NO_PAY);
    return null;
  }

  //ListView的Item
  Widget buildItem(BuildContext context, int index) {
    return GestureDetector(
      onTap: () {
        RouteUtil.goParameter(GoodDetailsPage(
          id: _listEntity[index].id,
        ));
      },
      child: Container(
        color: Colours.transparent,
        child: _xunchaItem(_listEntity[index]),
      ),
    );
  }

  Widget _xunchaItem(ShopOrder4AppRecordEntity entity) {
    return Container(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
        child: Column(
          children: <Widget>[
            SizedBox(
              height: 4,
            ),
            Container(
              alignment: Alignment.centerRight,
              child: WidgetUtils.getTextColorView(
                '等待买家付款',
                Colours.blackground_609,
                Dimens.FONT_SIZE_16,
              ),
            ),
            SizedBox(
              height: 4,
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    height: 110.0,
                    width: 110.0,
                    margin: const EdgeInsets.all(5.0),
                    child: FadeInImage.assetNetwork(
                      image: entity.fistImgUrl,
                      placeholder: 'images/picture_loading.png' /* 指定gif */,
                      fit: BoxFit.contain,
                    ),
                  ),
                  flex: 2,
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(left: 16),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        SizedBox(
                          height: 4,
                        ),
                        WidgetUtils.getTextColorView(
                          entity.name,
                          Colours.text_2222,
                          Dimens.FONT_SIZE_14,
                        ),
                        SizedBox(
                          height: 4,
                        ),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            WidgetUtils.getTextColorView(
                                '商品单价¥${entity.shopPrice}', Colours.text_2222, Dimens.FONT_SIZE_14),
                            SizedBox(
                              height: 4,
                            ),
                            WidgetUtils.getTextColorView('购买数量×${entity.shopCt}', Colours.gray_99, Dimens.FONT_SIZE_14,
                                decorationColor: Colours.gray_66),
                            SizedBox(
                              height: 4,
                            ),
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: const EdgeInsets.only(top: 4),
                              child: WidgetUtils.getTextColorView(
                                  '大陆地区包邮', Colours.blackground_609, Dimens.FONT_SIZE_14,
                                  overflow: TextOverflow.clip),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  flex: 3,
                ),
              ],
            ),
            SizedBox(
              height: 4,
            ),
            Container(
              alignment: Alignment.centerRight,
              child: WidgetUtils.getTextColorView(
                '实付款：¥${entity.shopAllPrice}',
                Colours.text_2222,
                Dimens.FONT_SIZE_16,
              ),
            ),
            SizedBox(
              height: 8,
            ),
            Container(
              alignment: Alignment.centerRight,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  GestureDetector(
                    onTap: () {
                      _bloc.cancelDate.add(entity.id);
                    },
                    child: WidgetUtils.showBoxBotton('取消订单',
                        borderColor: Colours.gray_91, textColor: Colours.gray_91, borderRadius: 20),
                  ),
                  SizedBox(
                    width: 8,
                  ),
                  GestureDetector(
                    onTap: () {
                      _orderId = entity.id;
                      _custGroupsRelaId = entity.custGroupsRelaId;
                      _detailsBloc.initDate.add(entity.commoditySpecId);
                    },
                    child: WidgetUtils.showBoxBotton('付款',
                        borderColor: Colours.blackground_609,
                        textColor: Colours.blackground_609,
                        borderRadius: 20,
                        horizontalPadding: 16),
                  ),
                ],
              ),
            ),
          ],
        ));
  }

  @override
  void dispose() {
    _playSubscription?.cancel();
    _deleteSubscription?.cancel();
    super.dispose();
  }
}
